package eg.com.itiga.ui.actions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessages;

import eg.com.itiga.business.factory.BusinessFactory;
import eg.com.itiga.business.user.UserService;
import eg.com.itiga.domain.Role;
import eg.com.itiga.domain.User;
import eg.com.itiga.ui.beans.LoginForm;

public class LoginAction extends org.apache.struts.action.Action {
    
	private final String admin = "Administrator";
	private final String itian = "ITIan";
	private final String company = "Company";

    
    public LoginAction() {
    }
    
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        // TODO: Write method body
        //throw new UnsupportedOperationException("Method is not implemented");
    	ActionForward forward = new ActionForward();
    	
    	UserService userService = BusinessFactory.createUserService();
    	User user = new User();
    	
    	user.setUserName(((LoginForm)form).getUserName());
    	user.setUserPassword(((LoginForm)form).getPassword());
    	user = userService.Login(user);
    	
    	if(user == null)
    	{
    		ActionErrors errors = new ActionErrors();
    		errors.add("InvalidLogin",new ActionError("InvalidLogin"));
    		saveErrors(request, errors);
    		forward = mapping.findForward("failLogin");
    	}
 
    	else {
    		request.setAttribute("id", user.getUserId());
    		String roleName = new String();
    		Role role = user.getRole();
    		if(role != null)
    			 roleName = role.getRName();
    		else
    			System.out.println("role is null");
    		if(roleName.equals(admin))
    			forward = mapping.findForward("successLogin1");
    		else if(roleName.equals(itian))
    			forward = mapping.findForward("successLogin2");
    		else if(roleName.equals(company))
    			forward = mapping.findForward("successLogin3");
    	}
    	
    	return forward;
    }

}